package org.alala.user.web.framework.controller;

import java.util.List;

import org.alala.user.data.models.User;
import org.alala.user.data.models.result.OKResult;
import org.alala.user.data.models.result.Result;
import org.alala.user.data.models.result.Results;
import org.alala.user.service.api.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class UserTestController {
	
	@Autowired
	private UserService userService;

	/**
	 * 简单例子，无参数，直接返回一段文本
	 * 例子:http://localhost:8080/user-web/test/hello
	 * 注意:produces是纯文本
	 * @return
	 */
	@RequestMapping(value="/hello", method = RequestMethod.GET, produces=MediaType.TEXT_PLAIN_VALUE)
	public String hello() {
		return "Hello,don't worry, I am working!";
	}
	
	
	/**
	 * 模拟数据查询，根据参数查询一个用户
	 * 参数是简单类型，返回一个对象，响应是json
	 * 注意:produces是json，编码utf8
	 * 例子:http://localhost:8080/user-web/test/search?name=alala
	 * @param name 名称
	 * @return 用户
	 */
	@RequestMapping(value="/search", method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public OKResult<List<User>> search(String name) {
		
		List<User> users = userService.search(name);
		
		return Results.newOkResult(users);
	}
	
	/**
	 * 模拟数据保存，保存一个用户数据
	 * 参数是用户对象，spring mvc会自动映射参数到字段
	 * 注意:produces是json，编码utf8
	 * 例子:http://localhost:8080/user-web/test/save?name=alala&age=12
	 * @param name 名称
	 * @param age 年龄
	 * @return 用户
	 */
	@RequestMapping(value="/save", method = { RequestMethod.GET, RequestMethod.POST}, produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public Result save(User user) {
		
		userService.save(user);
		
		return Results.newOkResult();
	}
	
}
